package com.gxh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gxh.dto.MachineDTO;
import com.gxh.dto.MachinePageQueryDTO;
import com.gxh.dto.MachineSaleDTO;
import com.gxh.dto.UserMachinePageQueryDTO;
import com.gxh.entity.*;
import com.gxh.exception.BaseException;
import com.gxh.mapper.*;
import com.gxh.result.PageResult;
import com.gxh.service.MachineService;
import com.gxh.utils.AliOssUtil;
import com.gxh.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MachineServiceImpl implements MachineService {

    @Autowired
    private MachineMapper machineMapper;
    @Autowired
    private MachineImageMapper machineImageMapper;
    @Autowired
    private MachineVideoMapper machineVideoMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private LocationMapper locationMapper;
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private UserHistoryMapper userHistoryMapper;
    @Autowired
    private FavoriteMapper favoriteMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private MachineSaleMapper machineSaleMapper;

    /**
     * 分页查询设备信息
     * @param machinePageQueryDTO
     * @return
     */
    public PageResult pageQuery(MachinePageQueryDTO machinePageQueryDTO) {
        PageHelper.startPage(machinePageQueryDTO.getPage(), machinePageQueryDTO.getPageSize());
        //获取设备数据返回带categoryName和locationName 加上第一张图片
        Page <MachineVO> page = machineMapper.pageQuery(machinePageQueryDTO);
        //获取设备图片第一张
        long  total =  page.getTotal();
        List<MachineVO> records = page.getResult();
         return new PageResult(total , records);
    }

    /**
     * 新增设备
     * @param machineDTO
     */
    @Transactional
    public void saveWithMedia(MachineDTO machineDTO) {
        // 插入设备表
        Machine machine = new Machine();
        BeanUtils.copyProperties(machineDTO, machine);
        machine.setStatus(0);//默认为0不推荐
        machine.setViewCount(0);
        machine.setIsSold(0);//默认为0未售出
        machineMapper.insertMachine(machine);

        Long machineId = machine.getId();

        // 插入图片（如果不为空）
        List<MachineImage> images = machineDTO.getImages();
        if (images != null && !images.isEmpty()) {
            for (MachineImage image : images){
                 image.setMachineId(machineId);
            }
             machineImageMapper.insertBatchImage(images);
        }


        // 插入视频（如果不为空）
        List<MachineVideo> videos = machineDTO.getVideos();
        if (videos  != null && !videos.isEmpty()) {
            for (MachineVideo  video : videos){
                video.setMachineId(machineId);
            }
            machineVideoMapper.insertBatchVideo(videos);
        }
    }


    /**
     * 根据id查询设备信息
     *
     * @param id
     * @return
     */
    public MachineDetailAdminVO getById(Long id) {
        Machine machine = machineMapper.selectById(id);
        if (machine == null) {
            return null;
        }
        Employee createUser = employeeMapper.selectById(machine.getCreateUser());
        Employee updateUser = employeeMapper.selectById(machine.getUpdateUser());
        MachineDetailAdminVO machineDetailAdminVO = new MachineDetailAdminVO();
        BeanUtils.copyProperties(machine, machineDetailAdminVO);
        machineDetailAdminVO.setCreateUser(createUser.getName());
        machineDetailAdminVO.setUpdateUser(updateUser.getName());

        // 分类名称
        Category category = categoryMapper.selectById(machine.getCategoryId());
        if (category != null) {
            machineDetailAdminVO.setCategoryName(category.getName());
        }

        // 位置（省市）- 只查一次
        Location location = locationMapper.selectById(machine.getLocationId());
        if (location != null) {
            machineDetailAdminVO.setProvince(location.getProvince());
            machineDetailAdminVO.setCity(location.getCity());
        }

        // 多图
        machineDetailAdminVO.setImages(
                machineImageMapper.selectList(
                        new QueryWrapper<MachineImage>().eq("machine_id", id)
                )
        );

        // 多视频
        machineDetailAdminVO.setVideos(
                machineVideoMapper.selectList(
                        new QueryWrapper<MachineVideo>().eq("machine_id", id)
                )
        );

        return machineDetailAdminVO;
    }

    /**
     * 修改设备信息
     * @param machineDTO
     */
    @Transactional
    public void updateWithMedia(MachineDTO machineDTO) {
        Machine machine = new Machine();
        BeanUtils.copyProperties(machineDTO, machine);
        machineMapper.updateMachine(machine);

        // 更新图片
        List<MachineImage> images = machineDTO.getImages();
        if (!images.isEmpty()) {
            machineImageMapper.delete(new QueryWrapper<MachineImage>().eq("machine_id", machine.getId()));
            // 插入新图
            for (MachineImage img : images) {
                img.setMachineId(machine.getId());
            }
            machineImageMapper.insertBatchImage(images);
        }

        // 更新视频
        List<MachineVideo> videos = machineDTO.getVideos();
        if (!videos.isEmpty()) {

            machineVideoMapper.delete(new QueryWrapper<MachineVideo>().eq("machine_id", machine.getId()));
            for (MachineVideo video : videos) {
                video.setMachineId(machine.getId());
            }
            machineVideoMapper.insertBatchVideo(videos);
        }
    }


    /**
     * 批量删除设备
     * @param ids
     */
    @Transactional
    public void deleteBatch(List<Long> ids) {
        // 删除图片
        QueryWrapper<MachineImage> imageQuery = new QueryWrapper<>();
        imageQuery.in("machine_id", ids);
        List<MachineImage> images = machineImageMapper.selectList(imageQuery);
        if (!images.isEmpty()) {
            List<String> imageObjectNames = images.stream()
                    .map(img -> aliOssUtil.extractObjectName(img.getImgUrl()))
                    .collect(Collectors.toList());
            aliOssUtil.deleteBatchOss(imageObjectNames);
        }

        // 删除视频
        QueryWrapper<MachineVideo> videoQuery = new QueryWrapper<>();
        videoQuery.in("machine_id", ids);
        List<MachineVideo> videos = machineVideoMapper.selectList(videoQuery);
        if (!videos.isEmpty()) {
            List<String> videoObjectNames = videos.stream()
                    .map(v -> aliOssUtil.extractObjectName(v.getVideoUrl()))
                    .collect(Collectors.toList());
            aliOssUtil.deleteBatchOss(videoObjectNames);
        }
        //删除用户收藏表和历史记录表
        favoriteMapper.delete(new QueryWrapper<Favorite>().in("machine_id", ids));
        userHistoryMapper.delete(new QueryWrapper<UserHistory>().in("machine_id", ids));
        // 删除数据库中的设备
        machineMapper.deleteBatchIds(ids);
    }


    /**
     * 用户端分页查询
     * @param userMachinePageQueryDTO
     * @return
     */
    public PageResult userPageQuery(UserMachinePageQueryDTO userMachinePageQueryDTO) {
        PageHelper.startPage(userMachinePageQueryDTO.getPage(), userMachinePageQueryDTO.getPageSize());
        Page <MachineItemVO> page = machineMapper.UserPageQuery(userMachinePageQueryDTO);
        long total = page.getTotal();
        List<MachineItemVO> records = page.getResult();
        return new PageResult(total, records);
    }

    /**
     * 设备关键词搜索
     * @param keyword
     * @return
     */
    public List<MachineKWResultVO> search(String keyword) {
        List<MachineKWResultVO> machineKWResultVOS = machineMapper.search(keyword);
        return machineKWResultVOS;
    }

    /**
     * 获取最新设备
     * @return
     */
    public List<MachineItemVO> getNew() {
        //  获取前十最新设备包括第一张图片
        List<MachineItemVO> machineItemVOS = machineMapper.getNew();
        return machineItemVOS;
    }

    /**
     * 获取推荐设备
     * @return
     */
    public List<MachineItemVO> getRecommend() {
        List<MachineItemVO> machineItemVOS = machineMapper.getRecommend();
        return machineItemVOS;
    }

    /**
     * 修改设备状态是否推荐
     * @param status
     * @param id
     */

    public void updateStatus(Integer status, Long id) {
        // 只有当要设置为推荐时才进行限制判断
        if (status != null && status == 1) {
            // 查询当前已推荐的数量
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("status", 1);
            Long count = machineMapper.selectCount(queryWrapper);
            if (count >= 20) {
                throw new BaseException("推荐的设备不能超过20个");
            }
        }
        // 执行状态更新
        Machine machine = new Machine();
        machine.setId(id);
        machine.setStatus(status);
        machineMapper.updateMachine(machine);
    }

    /**
     * 获取在工厂的设备
     * @return
     */
    public List<MachineItemVO> getInFactory() {
        List<MachineItemVO> machineItemVOS = machineMapper.getInFactory();
        return machineItemVOS;
    }

    /**
     * 用户端查询设备详情
     * @param id
     * @return
     */
    public MachineDetailVO userGetById(Long id) {
        Machine machine = machineMapper.selectById(id);
        if (machine == null){
            throw new BaseException("设备不存在");
        }
        machineMapper.incrementViewCount(id);
        MachineDetailVO  machineDetailVO = new MachineDetailVO();
        BeanUtils.copyProperties(machine, machineDetailVO);
        Category category = categoryMapper.selectById(machine.getCategoryId());
        if (category != null){
            machineDetailVO.setCategoryName(category.getName());
        }
        Location location = locationMapper.selectById(machine.getLocationId());
        if (location != null){
            machineDetailVO.setProvince(location.getProvince());
            machineDetailVO.setCity(location.getCity());
        }
        machineDetailVO.setImages(machineImageMapper.selectList(new QueryWrapper<MachineImage>().eq("machine_id", id)));
        machineDetailVO.setVideos(machineVideoMapper.selectList(new QueryWrapper<MachineVideo>().eq("machine_id", id)));
        return machineDetailVO;
    }

    /**
     * 设备售出
     * @param machineSaleDTO
     */
    public void sold(MachineSaleDTO machineSaleDTO) {
        // 保存售出信息
        machineSaleDTO.setCreateTime(LocalDateTime.now());
        MachineSale machineSale = new MachineSale();
        BeanUtils.copyProperties(machineSaleDTO, machineSale);
        machineSaleMapper.insert(machineSale);
        // 更新主表设备售出状态
        Machine machine = new Machine();
        machine.setId(machineSaleDTO.getMachineId());
        machine.setIsSold(1);
        machine.setSoldTime(LocalDateTime.now());
        machineMapper.updateById(machine);
    }


}
